import React, { memo, useCallback, useMemo, useState } from "react";

interface IProps {
  handleClick: () => void;
}
//setNum 不停更新组件,使用memo缓存组件,没变化不更新-相当于shouldComponentUpdate
const Sub = memo((props: IProps) => {
  console.log("子组件被触发了");
  return (
    <>
      <p>子组件内容</p>
      <button onClick={props.handleClick}>累加</button>
    </>
  );
});

export default function App4() {
  const [num, setNum] = useState(0);

  /* 
  setNum(num+1)
  setNum (num=>num+1)
  */

  //真正被触发的函数
  //当存在父子组件关系时，usecallback必须搭配memo一起使用
  const handleClick = useCallback(() => {
    setNum((num) => num + 1);
  }, []);

  //useMemo比useCallback多嵌套一个函数
  //   useMemo()写法
  //   const handleClick = useMemo(() => {
  //     return () => setNum((num) => num + 1);
  //   }, []);

  return (
    <div>
      <h2>{num}</h2>
      <Sub handleClick={handleClick} />
    </div>
  );
}
